#!/bin/sh
#
# $Id: postinst 49 2011-12-01 19:09:52Z imooreyahoo@gmail.com $
#
# see: dh_installdeb(1)

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

case "$1" in
    configure)

	# Check for XML config
	if ! omv_config_exists "//services/cups"; then
		omv_config_add_element "//services" "cups" ""
	fi
	
    if ! omv_config_exists "//services/cups/enable"; then
    
        omv_config_add_element "//services/cups" "enable" "0"
        
        $(/etc/init.d/cups status >/dev/null && omv_config_update "//services/cups/enable" "1") || /bin/true
        
    fi

    if ! omv_config_exists "//services/cups/airprint"; then
    	omv_config_add_element "//services/cups" "airprint" "0"
    fi
	
	# Fix permissions
	omv_install_fixperms
	
    # Add lpadmin to OMV
    if ! omv_config_exists "//system/usermanagement/groups/group[name='lpadmin']"; then
    
        omv_config_import_group "lpadmin"
        omv_config_update "//system/usermanagement/groups/group[name='lpadmin']/comment" "Printer Administrators"
        
        usermod -a -G lpadmin admin
        
        admingroups="$(omv_config_get "//system/usermanagement/users/user[name='admin']/groups")"
        
        if [ $(echo "${admingroups}" | grep -c "lpadmin") -lt 1 ]; then
        	
        	if [ "${admingroups}" != "" ]; then
        		admingroups="${admingroups},"
        	fi
        	
        	omv_config_update "//system/usermanagement/users/user[name='admin']/groups" "${admingroups}lpadmin"
        fi
    fi

	# For samba printer driver share
	chgrp -R lpadmin /var/lib/samba/printers
	chmod -R g+w /var/lib/samba/printers
	
	# Make sure python scripts are setup correctly
	chown root /usr/local/bin/omvcups.py
	chmod 500 /usr/local/bin/omvcups.py
	chown root /usr/local/bin/omvcups-avahi.py
	chmod 500 /usr/local/bin/omvcups-avahi.py
	
	
	# Perform actions if we're enabled
	if [ "$(omv_config_get "//services/cups/enable")" = "1" ]; then

		# Generate cups config
		omv-mkconf cups
		
		# Restart cups
		/etc/init.d/cups restart
			
		# Avahi files
		/usr/local/bin/omvcups-avahi.py
		
		# Generate samba confing
		omv-mkconf samba
	
		if [ "$(omv_config_get "//services/smb/enable")" = "1" ]; then
			/etc/init.d/samba restart
		fi

		
	fi
		
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
